package com.wx.disparent.mallparent.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wx.disparent.mallparent.commons.util.PageResult;
import com.wx.disparent.mallparent.commons.util.PageUtil;
import com.wx.disparent.mallparent.entity.ParaEntity;
import com.wx.disparent.mallparent.entity.ProblemEntity;
import com.wx.disparent.mallparent.entity.ProductEntity;
import com.wx.disparent.mallparent.entity.UserEntity;
import com.wx.disparent.mallparent.service.AdminUserService;
import com.wx.disparent.mallparent.service.ParaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminUserController {

    @Autowired
    private AdminUserService adminUserService ;

    @Autowired
    private ParaService paraService ;

    @RequestMapping(value = "/login")
    public String loginPage(){
        return "web/pc/loginPage";
    }

    @RequestMapping(value = "/user/updatePw")
    public ModelAndView updatePw(@RequestParam(value = "id")Integer id){
        UserEntity userEntity = adminUserService.findById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/web/pc/updatePwPage");
        modelAndView.addObject("userEntity",userEntity);
        return modelAndView;
    }

    @RequestMapping(value = "/user/updatePwCheck",method = RequestMethod.POST )
    @ResponseBody
    public Map<String, Object> updatePwCheck(UserEntity userEntity){
        Map<String, Object> updatePwCheckMap = adminUserService.updatePwCheck(userEntity);
        return updatePwCheckMap;
    }

    @RequestMapping(value = "/user/sureUpdatePw",method = RequestMethod.POST)
    public ModelAndView sureUpdatePw(@RequestParam(value = "id")Integer id,
                                     @RequestParam(value = "newPw")String newPw,
                                     HttpSession httpSession){
        UserEntity userEntity = new UserEntity();
        userEntity.setPasswd(newPw);
        userEntity.setId(id);
        int update = adminUserService.updatePassWdById(userEntity);
        UserEntity byId = adminUserService.findById(id);
        httpSession.setAttribute("userEntity",byId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("out");
        modelAndView.addObject("userEntity",userEntity);
        return modelAndView;

    }

    @RequestMapping(value = "/user/userInfoCheck",method = RequestMethod.POST )
    @ResponseBody
    public Map<String, Object> userInfoCheck(UserEntity userEntity, HttpSession httpSession){
        Map<String, Object> userInfoCheckMap = adminUserService.userInfoCheck(userEntity);
        return userInfoCheckMap;
    }

    @RequestMapping(value = "/user/sureUpdateUserInfo",method = RequestMethod.POST )
    @ResponseBody
    public ModelAndView sureUpdateUserInfo(UserEntity userEntity, HttpSession httpSession){
        Integer i = adminUserService.updateById(userEntity);
        UserEntity byId = adminUserService.findById(userEntity.getId());
        httpSession.setAttribute("userEntity",byId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("out");
        modelAndView.addObject("userEntity",byId);
        return modelAndView;
    }

    @RequestMapping(value = "/user/updateCheck",method = RequestMethod.POST )
    @ResponseBody
    public Map<String, Object> updateCheck(UserEntity userEntity){
        Map<String, Object> updateCheckMap = adminUserService.updateCheck(userEntity);
        return updateCheckMap;
    }

    @RequestMapping(value = "/user/userInfo")
    public ModelAndView userInfo(@RequestParam(value = "id")Integer id){
        UserEntity userEntity = adminUserService.findById(id);
        List<ProblemEntity> problemEntityList = adminUserService.findAllProblem();
        Map<String,String> paraMap = new HashMap<>();
        paraMap.put("paraid","bankcard_type");
        List<ParaEntity> acctTypeParaEntityList = paraService.findAllAcctTypePara(paraMap);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("web/pc/userInfo");
        modelAndView.addObject("userEntity",userEntity);
        modelAndView.addObject("problemEntityList", problemEntityList);
        modelAndView.addObject("acctTypeParaEntityList",acctTypeParaEntityList);
        return modelAndView;
    }

    @RequestMapping(value = "/user/addCheck",method = RequestMethod.POST )
    @ResponseBody
    public Map<String, Object> addCheck(UserEntity userEntity){
        Map<String, Object> addCheckMap = adminUserService.addCheck(userEntity);
        return addCheckMap;
    }

    @RequestMapping(value = "/user/sureUpdate",method = RequestMethod.POST )
    @ResponseBody
    public ModelAndView sureUpdate(UserEntity userEntity, HttpSession httpSession,HttpServletRequest request){

        Integer i = adminUserService.updateById(userEntity);

        UserEntity sessionUserEntity = (UserEntity)httpSession.getAttribute("userEntity");
        UserEntity byId = adminUserService.findById(userEntity.getId());
        if(sessionUserEntity.getId() == userEntity.getId()){
            httpSession.setAttribute("userEntity",byId);
        }

        int pageSize = PageUtil.getPage(request,"pageSize") ;
        int pageNum = PageUtil.getPage(request,"pageNum") ;
        PageInfo pageInfo= adminUserService.findAll(pageNum,pageSize);
        List list = pageInfo.getList();
        ModelAndView mv = new ModelAndView() ;
        mv.addObject("usersList",list);
        mv.setViewName("web/pc/usersPage");
        return mv;
    }

    @RequestMapping(value = "/user/sureAdd",method = RequestMethod.POST )
    @ResponseBody
    public ModelAndView sureAdd(UserEntity userEntity, HttpSession httpSession,HttpServletRequest request){
        Integer i = adminUserService.insert(userEntity);

        int pageSize = PageUtil.getPage(request,"pageSize") ;
        int pageNum = PageUtil.getPage(request,"pageNum") ;
        PageInfo pageInfo= adminUserService.findAll(pageNum,pageSize);
        List list = pageInfo.getList();
        ModelAndView mv = new ModelAndView() ;
        mv.addObject("usersList",list);
        mv.setViewName("web/pc/usersPage");
        return mv;
    }


    @RequestMapping(value = "/user/search")
    @ResponseBody
    public PageInfo search(HttpServletRequest request,@RequestParam String searchContext){
        int pageSize = PageUtil.getPage(request,"pageSize") ;
        int pageNum = PageUtil.getPage(request,"pageNum") ;
        PageInfo<UserEntity> searchPageInfo=adminUserService.search(pageSize,pageNum,searchContext);
        return searchPageInfo;
    }

    @RequestMapping(value = "/user/update")
    public ModelAndView update(@RequestParam(value = "id")Integer id){
        UserEntity userEntity = adminUserService.findUserEntityById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("web/pc/updatePage");
        modelAndView.addObject("userEntity",userEntity);
        return modelAndView;
    }

    @RequestMapping(value = "/user/resetPw")
    public ModelAndView resetPw(@RequestParam(value = "id")Integer id,HttpServletRequest request){
        Integer i = adminUserService.resetPw(id);
        int pageSize = PageUtil.getPage(request,"pageSize") ;
        int pageNum = PageUtil.getPage(request,"pageNum") ;
        PageInfo pageInfo= adminUserService.findAll(pageNum,pageSize);
        List list = pageInfo.getList();
        ModelAndView mv = new ModelAndView() ;
        mv.addObject("usersList",list);
        mv.setViewName("web/pc/usersPage");
        return mv;
    }



    @RequestMapping(value = "/user/add")
    public ModelAndView add(){
        UserEntity userEntity = null;
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("web/pc/addPage");
        modelAndView.addObject("userEntity",userEntity);
        return modelAndView;
    }




    @RequestMapping(value = "/user/usersPage")
    public ModelAndView usersPage(HttpServletRequest request, HttpSession session){
//        int pageSize = PageUtil.getPage(request,"pageSize") ;
//        int pageNum = PageUtil.getPage(request,"pageNum") ;
//        PageInfo pageInfo= adminUserService.findAll(pageNum,pageSize);
//        List list = pageInfo.getList();
        ModelAndView mv = new ModelAndView() ;
//        mv.addObject("usersList",list);
        mv.setViewName("web/pc/usersPage");
        return mv;
    }

    @RequestMapping("/user/lowerAndReferList")
    @ResponseBody
    public String lowerAndReferList(@RequestParam("aoData") String aoData,@RequestParam("type")String type,HttpSession session) {
        PageResult pr = new PageResult(aoData);
        String searchContext = pr.getSearch();

        JSONArray jsonArray = new JSONArray();

        // 从数据库查询，这里返回的的allUser就已经分页成功了
        List<UserEntity> entities = null;
        UserEntity userEntity = (UserEntity) session.getAttribute("userEntity");
        if(type.equals("lowerUser")&& searchContext.equals("")) {
            entities = adminUserService.findLowerUsers(userEntity.getId());
        } else if(type.equals("lowerUser")&& !searchContext.equals("")){
            entities = adminUserService.lowerSearch(searchContext,userEntity.getId());
        } else if(type.equals("referUser")&& searchContext.equals("")) {
            entities = adminUserService.findReferUsers(userEntity.getReferId());
        } else if(type.equals("referUser")&& !searchContext.equals("")){
            entities = adminUserService.referSearch(searchContext,userEntity.getReferId());
        }

        PageInfo<UserEntity> page = new PageInfo<>(entities);

        for (Object obj : entities) {
            UserEntity entity = (UserEntity) obj;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("phone", entity.getPhone());


            if(entity.getUsername() == null||entity.getUsername()==""){
                jsonObject.put("username","");
            }else{
                jsonObject.put("username", entity.getUsername());
            }
            if(entity.getRealName() == null||entity.getRealName()==""){
                jsonObject.put("realname", "");
            }else{
                jsonObject.put("realname", entity.getRealName());
            }
            if(entity.getEmail() == null||entity.getEmail()==""){
                jsonObject.put("email", "");
            }else{
                jsonObject.put("email", entity.getEmail());
            }

            if(entity.getAlipayName() == null||entity.getAlipayName()==""){
                jsonObject.put("alipayname", "");
            }else{
                jsonObject.put("alipayname", entity.getAlipayName());
            }

            if(entity.getAlipayNum() == null||entity.getAlipayNum()==""){
                jsonObject.put("alipaynum", "");
            }else{
                jsonObject.put("alipaynum", entity.getAlipayNum());
            }

            if(entity.getWechatName() == null||entity.getWechatName()==""){
                jsonObject.put("wechatname", "");
            }else{
                jsonObject.put("wechatname", entity.getWechatName());
            }

            if(entity.getWechatNum() == null||entity.getWechatNum()==""){
                jsonObject.put("wechatnum", "");
            }else{
                jsonObject.put("wechatnum", entity.getWechatNum());
            }

            if(entity.getBackcardName() == null||entity.getBackcardName()==""){
                jsonObject.put("backcardname", "");
            }else{
                jsonObject.put("backcardname", entity.getBackcardName());
            }

            if(entity.getBankcardName() == null||entity.getBankcardName()==""){
                jsonObject.put("bankcardname", "");
            }else{
                jsonObject.put("bankcardname", entity.getBankcardName());
            }

            if(entity.getBankcardNum() == null||entity.getBankcardNum()==""){
                jsonObject.put("bankcardnum", "");
            }else{
                jsonObject.put("bankcardnum", entity.getBankcardNum());
            }


            if(entity.getLastLogin() == null||entity.getLastLogin()==""){
                jsonObject.put("lastlogin", "");
            }else{
                jsonObject.put("lastlogin", entity.getLastLogin());
            }
            jsonArray.add(jsonObject);
        }

        String json = "{\"sEcho\":" + (pr.getsEcho()+1) + ",\"iTotalRecords\":" + page.getTotal() + ",\"iTotalDisplayRecords\":" + page.getTotal() + ",\"aaData\":" + jsonArray.toString() + "}";

        return json;
    }

    @RequestMapping("/user/usersList")
    @ResponseBody
    public String usersList(@RequestParam("aoData") String aoData,@RequestParam("type")String type,HttpSession session) {
        PageResult pr = new PageResult(aoData);
        String searchContext = pr.getSearch();

        JSONArray jsonArray = new JSONArray();

        // 从数据库查询，这里返回的的allUser就已经分页成功了
        List<UserEntity> entities = null;
        UserEntity userEntity = (UserEntity) session.getAttribute("userEntity");
        if (type.equals("allUser")&& searchContext.equals("")) {
            entities = adminUserService.findAll(null);
        } else if(type.equals("allUser")&& !searchContext.equals("")){
            entities = adminUserService.search(searchContext);
        }

        PageInfo<UserEntity> page = new PageInfo<>(entities);

        for (Object obj : entities) {
            UserEntity entity = (UserEntity) obj;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("phone", entity.getPhone());
            if(entity.getUsername() == null||entity.getUsername()==""){
                jsonObject.put("username","");
            }else{
                jsonObject.put("username", entity.getUsername());
            }
            if(entity.getRealName() == null||entity.getRealName()==""){
                jsonObject.put("realname", "");
            }else{
                jsonObject.put("realname", entity.getRealName());
            }
            if(entity.getEmail() == null||entity.getEmail()==""){
                jsonObject.put("email", "");
            }else{
                jsonObject.put("email", entity.getEmail());
            }
            if(entity.getLastLogin() == null||entity.getLastLogin()==""){
                jsonObject.put("lastlogin", "");
            }else{
                jsonObject.put("lastlogin", entity.getLastLogin());
            }
            jsonObject.put("operation", entity.getId());
            jsonArray.add(jsonObject);
        }

        String json = "{\"sEcho\":" + (pr.getsEcho()+1) + ",\"iTotalRecords\":" + page.getTotal() + ",\"iTotalDisplayRecords\":" + page.getTotal() + ",\"aaData\":" + jsonArray.toString() + "}";

        return json;
    }

    @RequestMapping(value = "/user/referPage")
    public ModelAndView referPage(HttpSession session){
       /* UserEntity userEntity = (UserEntity)session.getAttribute("userEntity");
        List<UserEntity> referList = adminUserService.findReferUsers(userEntity.getReferId());*/
        ModelAndView mv = new ModelAndView() ;
        /*mv.addObject("usersList",referList);*/
        mv.setViewName("web/pc/referPage");
        return mv;
    }

    @RequestMapping(value = "/user/lowerPage")
    public ModelAndView lowerPage(HttpServletRequest request, HttpSession session){
       /* UserEntity userEntity = (UserEntity)session.getAttribute("userEntity");
        List<UserEntity> lowerList = adminUserService.findLowerUsers(userEntity.getId());*/
        ModelAndView mv = new ModelAndView();
        /*mv.addObject("usersList",lowerList);*/
        mv.setViewName("web/pc/lowerPage");
        return mv;
    }

    @RequestMapping(value = "/user/login",method = RequestMethod.POST )
    @ResponseBody
    public Map<String, Object> login(@RequestParam(value = "nameOrPhone")String nameOrPhone,
                                     @RequestParam(value = "passwd")String passwd,
                                     HttpSession session){
        Map<String, Object> loginMap = adminUserService.login(nameOrPhone,passwd);
        if(loginMap.get("isSuccess").equals("true")){
            session.setAttribute("userEntity",loginMap.get("userEntity"));
        }
        return loginMap;
    }


}
